package com.cloud.phone.task;

import android.view.accessibility.AccessibilityNodeInfo;

import com.cloud.phone.base.BaseApp;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.service.AccessibilityAutoMainService;
import com.cloud.phone.task.bean.ServerTaskDataBean;
import com.cloud.phone.task.bean.UserInfo;
import com.cloud.phone.task.taskCongfig.TaskTypeConfig;
import com.cloud.phone.task.tiktok.TikTokTask;
import com.cloud.phone.task.whatsapp.WhatsAppTask;
import com.cloud.phone.task.whatsapp.WhatsAppTaskDealTool;
import com.cloud.phone.tools.AccessibilityTool;
import com.cloud.phone.utils.AppUtils;
import com.cloud.phone.view.TsUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务管理器
 */
public class TaskManager {
    private static TaskManager taskManager;
    public List<BaseTask> tasks=new ArrayList<>();
    public AccessibilityNodeInfo currentRootNode;
    public AccessibilityAutoMainService accessibilityService;
    public UserInfo currentTiktokUserInfo;
    public static boolean isRegisterTaskDoing;
    /**
     * 获取单例
     * @return
     */
    public static TaskManager getInstance(){
        if(taskManager==null){
            taskManager=new TaskManager();
        }
        return taskManager;
    }


    public void setAccessibilityService(AccessibilityAutoMainService accessibilityService) {
        this.accessibilityService = accessibilityService;
        for(int i=0;i<tasks.size();i++){
            BaseTask task=tasks.get(i);
            if(task!=null) {
                task.setAccessibilityService(accessibilityService);
            }
        }
    }

    public BaseTask getCurrentTask(){
        try {
            if(tasks!=null&& !tasks.isEmpty()){
                return tasks.get(0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建一个tiktok任务
     */
    public BaseTask createTikTokTask(ServerTaskDataBean serverTaskDataBean){
        TikTokTask task=new TikTokTask();
        task.setServerTaskDataBean(serverTaskDataBean);
        task.setAccessibilityService(accessibilityService);
        task.addOrReplaceToTaskList();
        return task;
    }


    /**
     * 创建一个whatsApp任务
     * @param serverTaskDataBean
     */
    public BaseTask createWhatsTask(ServerTaskDataBean serverTaskDataBean){
        WhatsAppTask task=new WhatsAppTask();
        task.setServerTaskDataBean(serverTaskDataBean);
        task.setAccessibilityService(accessibilityService);
        task.addOrReplaceToTaskList();
        return task;
    }


    /**
     * 在无障碍服务页面变化时会触发这个方法
     */
    public void onTaskDoing() throws InterruptedException {
        if(isDealingWhatsAppChatList){
            MsgTaskManger.showLog("正在处理聊天列表");
            return;
        }
        currentRootNode = AccessibilityTool.getInstance().getRootNodeInfo(accessibilityService);
        if (tasks != null&& !tasks.isEmpty()) {
            //只要任务列表中有任务便取第一个任务判断任务是否待开始
            BaseTask task=tasks.get(0);
//            MsgTaskManger.showLog("执行的任务：type="+task.currentTaskType+"/status="+task.taskStatus);
            if(task.taskStatus==BaseTask.ON_START_TASK) {
                MsgTaskManger.showLog("onTaskDoing--->ON_START_TASK taskType=" + task.currentTaskType);
            }
            if(task.service==null){
                task.setAccessibilityService(accessibilityService);
            }
            if(task.taskStatus==BaseTask.WAIT) {
                //待开始的任务就开始任务
                task.changeTaskStatusToStart();
            }else if(task.taskStatus==BaseTask.ON_START_TASK) {
                //待开始的任务就开始任务
                task.doTask();
            }else if(task.taskStatus==BaseTask.RUNNING_TASK) {
                //任务正在运行
                if(task instanceof TikTokTask) {
                    checkIsAutoTaskAndIsInTikTok();
                }else if(task instanceof WhatsAppTask){
                    checkIsInWhatsApp(task);
                }
            }else if(task.taskStatus==BaseTask.FINISH){
                //任务做完之后在manager里面将任务移除，3秒轮询自动开启后面的任务
            }else if(task.taskStatus==BaseTask.ERR){
                //任务出现错误
            }else if(task.taskStatus==BaseTask.STOP){
                //任务停止了
            }

            if(task.taskStatus>2){
                dealWithWhatsAppChatList(task);
            }
        }else{
            dealWithWhatsAppChatList(null);
        }
    }


    /**
     * 处理每隔几秒更新列表信息的任务
     */
    public static boolean isDealingWhatsAppChatList=false;
    public static int currentTaskAppType=TaskTypeConfig.CURRENT_TYPE_WHATSAPP;
    private void dealWithWhatsAppChatList(BaseTask task) throws InterruptedException {
        if(task==null&&currentTaskAppType==TaskTypeConfig.CURRENT_TYPE_WHATSAPP){
            MsgTaskManger.showLog("创建一个whatsApp空闲任务");
            //空闲时，判断若是当前app类型是whatsApp，需要在空闲时刷新APP
            task=createWhatsTask(new ServerTaskDataBean());
            task.taskStatus=BaseTask.FINISH;
        }
        if(task instanceof WhatsAppTask){
            if(task.taskStatus!=BaseTask.FINISH&&task.taskStatus!=BaseTask.ERR){
                return;
            }
            WhatsAppTask whatsAppTask= (WhatsAppTask) task;
            if (whatsAppTask.whatsAppTaskDealTool == null) {
                whatsAppTask.whatsAppTaskDealTool = new WhatsAppTaskDealTool(whatsAppTask);
            }
            whatsAppTask.updateConversationListWhenFinishOrErr();
        }
    }



    private void checkIsInWhatsApp(BaseTask task) throws InterruptedException {
        if(AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(),Constants.whatsAppPackageName)) {
            //已安装app，再判断当前包名是否与要打开app一致
            if (!AccessibilityTool.getInstance().checkIsEnterInWhatsApp(accessibilityService)) {
                //打开whatsApp
                AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(), Constants.whatsAppPackageName);
                Thread.sleep(3000);
                task.onTaskErr("不在whatsApp，打开whatsApp");
                task.taskStatus=BaseTask.ON_START_TASK;
            }
        }else{
            task.onTaskErr("未安装whatsApp");
        }
    }


    /**
     * 如果任务非链接跳转类任务，则判断一下在任务执行中时是否在tiktok的app里面
     */
    private void checkIsAutoTaskAndIsInTikTok() throws InterruptedException {
        BaseTask task=tasks.get(0);
        if(task.currentTaskType!= TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_LIKE_BY_LINK
        &&task.currentTaskType!= TaskTypeConfig.TIKTOK_TASK_SINGLE_WORKS_COMMENT_BY_LINK){
            if(AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(),Constants.tiktokPackageName)) {
                if(!AccessibilityTool.getInstance().checkIsEnterInTikTok(accessibilityService)){
                    if(task.currentTaskType==TaskTypeConfig.TEST){
//                        String result = AccessibilityTool.getInstance().findNodeInfoAllInPage("", null, accessibilityService, "", false);
//                        Message message= Message.obtain();
//                        message.obj=result;
//                        EventBus.getDefault().post(message);
//                        task.taskStatus=TikTokTask.FINISH;
                        return;
                    }
                    //已安装tiktok，且未在tiktok页面
                    //判断是注册任务接收到消息后先清除tiktok的缓存
                    if(task.currentTaskType!=TaskTypeConfig.TIKTOK_TASK_AUTO_REGISTER){
                        //非注册任务
                        AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(),Constants.tiktokPackageName);
                        Thread.sleep(3000);
                        task.taskStatus=BaseTask.ON_START_TASK;
                    }else{
                        if(isRegisterTaskDoing){
                            return;
                        }
                        MsgTaskManger.dealWithAutoRegisterLauncher(task);
                    }
                }
            }else{
                //未安装tiktok的
                task.onTaskErr("未安装tikTok");
            }
        }else{
            //当前任务执行中并且是链接跳转类任务---点赞某作品、评论某作品
            if(!AppUtils.Companion.isAppInstall(BaseApp.app.getApplicationContext(),Constants.tiktokPackageName)) {
                //未安装tiktok的
                task.onTaskErr("未安装tikTok");
            }else{
                if(!TikTokTask.isJumpToWebOnce){
                    AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(),Constants.tiktokPackageName);
                    Thread.sleep(1000);
                    task.taskStatus=BaseTask.ON_START_TASK;
                }
            }
        }
    }


    public void onOpenTaskApp(BaseTask baseTask,String packageName){
        if(accessibilityService==null){
            TsUtils.showTips("无障碍服务未开启");
            return;
        }
        if(baseTask==null){
            TsUtils.showTips("当前任务为空");
            return;
        }
        String pkgName = AccessibilityTool.getInstance().getCurrentPagePackageName(accessibilityService);
        if(!packageName.equals(pkgName)){
            AppUtils.Companion.launchApp(BaseApp.app.getApplicationContext(), packageName);
        }

    }
}
